const { promisify } = require("util")
const path = require("path")
const download = promisify(require("download-git-repo"))
const inquirer = require("inquirer")
const ora = require("ora")
const chalk = require("chalk")


const { vueRepo } = require("../config/repo-config")
const { commandSpawn } = require("../utils/terminal")
const { compile, writeToFile, readFileContent, createDirSync, translationWord } = require("../utils/utils")
const instance = require("../utils/request")

const createProjectAction = async (project) => {
  const command = process.platform === "win32" ? "npm.cmd" : "npm"
  const spinner = ora(chalk.rgb(17, 168, 205).bgRgb(33, 44, 55)("clone project ...\n"))
  const spinner2 = ora(chalk.rgb(17, 168, 205).bgRgb(33, 44, 55)("install dependent...\n"))
  const spinner3 = ora(chalk.rgb(17, 168, 205).bgRgb(33, 44, 55)("start project ...\n"))

  try {
    // 1.clone项目
    spinner.start()
    await download(vueRepo, project, { clone: true })
    spinner.succeed(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)("clone project succeed!"))
  } catch (error) {
    spinner.fail(chalk.rgb(212, 66, 33).bgRgb(33, 44, 55)("clone project error"))
  }

  try {
    // 2.执行npm install
    spinner2.start()
    await commandSpawn(command, ["install"], { cwd: `./${project}` })
    spinner2.succeed(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)("install all dependent succeed!"))
  } catch (error) {
    spinner2.fail(chalk.rgb(212, 66, 33).bgRgb(33, 44, 55)("clone project error"))
  }

  try {
    // 3.运行npm run serve
    spinner3.start()
    commandSpawn(command, ["run", "serve"], { cwd: `./${project}` })
    spinner3.succeed(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)("start project succeed!"))
  } catch (error) {
    spinner3.fail(chalk.rgb(212, 66, 33).bgRgb(33, 44, 55)("start project error"))
  }

}

// 添加组件的 action
const addComponentAction = async (name, dest) => {
  const spinner = ora(chalk.rgb(17, 168, 205).bgRgb(33, 44, 55)("add component ...\n")).start()
  try {
    // 1.编译ejs模板
    const result = await compile("component", { name, lowerName: name.toLowerCase() })
    if (createDirSync(dest)) {
      // 2.生成vue组件
      const targetPath = path.resolve(dest, `${name}.vue`)
      // 3.写入文件
      writeToFile(targetPath, result)
      spinner.succeed(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)("add component succeed!"))
    }
  } catch (error) {
    spinner.fail(chalk.rgb(212, 66, 33).bgRgb(33, 44, 55)("add component error"))
  }
}

// 添加页面和路由的action
const addPageAndRouteAction = async (name, dest) => {
  const spinner = ora(chalk.rgb(17, 168, 205).bgRgb(33, 44, 55)("add page and route ...\n")).start()
  try {
    // 1.编译ejs模板
    const pageResult = await compile("component", { name, lowerName: name.toLowerCase() })
    const routeResult = await compile("router", { name, lowerName: name.toLowerCase() })
    // 2.生成vue页面/路由
    const realPath = path.resolve(dest, name.toLowerCase())
    if (createDirSync(realPath)) {
      const pagePath = path.resolve(realPath, `${name}.vue`)
      const routePath = path.resolve(realPath, "router.js")
      // 3.写入文件
      writeToFile(pagePath, pageResult)
      writeToFile(routePath, routeResult)
      spinner.succeed(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)("add page and route succeed!"))
    }
  } catch (error) {
    spinner.fail(chalk.rgb(212, 66, 33).bgRgb(33, 44, 55)("add page and route error"))
  }
}

// 添加store的action
const addStoreAction = async (name, dest) => {
  const spinner = ora(chalk.rgb(17, 168, 205).bgRgb(33, 44, 55)("add store ...\n")).start()
  try {
    // 1.编译ejs模板
    const storeResult = await compile("store", {})
    const typesResult = await compile("store-types", {})
    // 2.生成vue页面/路由
    const realPath = path.resolve(dest, name.toLowerCase())
    if (createDirSync(realPath)) {
      const storePath = path.resolve(realPath, "index.js")
      const typesPath = path.resolve(realPath, "types.js")
      // 3.写入文件
      writeToFile(storePath, storeResult)
      writeToFile(typesPath, typesResult)
      spinner.succeed(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)("add store succeed!"))
    }
  } catch (error) {
    spinner.fail(chalk.rgb(212, 66, 33).bgRgb(33, 44, 55)("add store error"))
  }
}

// 翻译
const translationWordAction = async (words, inFileName, outFileName) => {
  let word = null;
  let result = null
  let isTranslationWord = false
  const spinner = ora(chalk.rgb(17, 168, 205).bgRgb(33, 44, 55)("正在翻译...\n")).start()

  try {
    if (words.length > 0) {
      word = words.join(" ").trim()
    } else if (inFileName) {
      const content = await readFileContent(inFileName)
      word = content.trim()
      words = /[\u4E00-\u9FA5]/.test(word[0]) ? ["中文"] : ['English']
    } else {
      spinner.fail(chalk.rgb(212, 66, 33).bgRgb(33, 44, 55)("参数格式不对哦"))
      return;
    }

    if (/[\u4E00-\u9FA5]/.test(words[0])) {
      // 中文转英文
      result = await instance.get(`http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=${encodeURI(word)}`)
      // result = await instance.get(`http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&sl=auto&tl=en_TW&q=${encodeURI(word)}`)
    } else {
      // 英文转中文
      result = await instance.get(`http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=${encodeURI(word)}`)
      // result = await instance.get(`http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&sl=auto&tl=zh_TW&q=${encodeURI(word)}`)
      isTranslationWord = true
    }

    if (!outFileName) {
      // for (const item of result.sentences) {
      for (const item of result.translateResult[0]) {
        if (isTranslationWord) {
          spinner.info(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)(translationWord(item.tgt)))
          // spinner.info(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)(translationWord(item.trans)))
        } else {
          spinner.info(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)(item.tgt))
          // spinner.info(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)(item.trans))
        }
      }
    }

    if (outFileName) {
      // 文件输出
      if (createDirSync(outFileName)) {
        const filePath = path.resolve(outFileName, "translate.txt")
        // 3.写入文件
        if (isTranslationWord) {
          await writeToFile(filePath, translationWord(result.sentences[0].trans))
        } else {
          await writeToFile(filePath, result.sentences[0].trans)
        }
      }
      spinner.succeed(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)("结果写入文件成功!"))
    }
  } catch (error) {
    spinner.fail(chalk.rgb(212, 66, 33).bgRgb(33, 44, 55)("sorry 翻译失败~"))
  }

}

// git 提交
const commitToGitAction = async (word) => {
  const spinner = ora(chalk.rgb(17, 168, 205).bgRgb(33, 44, 55)("git push ...\n")).start()
  try {
    const command = process.platform === "win32" ? "git" : "git"
    await commandSpawn(command, ["pull"])
    await commandSpawn(command, ["add", "."])
    await commandSpawn(command, ["commit", `-m${word}`])
    await commandSpawn(command, ["push"])
    spinner.succeed(chalk.rgb(13, 188, 121).bgRgb(33, 44, 55)("git push succeed!"))
  } catch (error) {
    spinner.fail(chalk.rgb(212, 66, 33).bgRgb(33, 44, 55)("git push error"))
  }
}

// 询问
const tempAction = async () => {
  const res = await inquirer.prompt([
    {
      type: "input",
      name: "auther",
      message: "你叫啥名字"
    }
  ])
  console.log("感谢使用", res);
}

module.exports = {
  createProjectAction,
  addComponentAction,
  addPageAndRouteAction,
  addStoreAction,
  tempAction,
  translationWordAction,
  commitToGitAction
}
